const enterpriseVue = new Vue({
    el: '#app',
    data() {
        return {
            rules: {
                Supplier_SerialNumber: [{ required: true, message: '请选择供应商', trigger: 'change' }],
                Purchase_Date: [{ required: true, message: '请输入采购日期', trigger: 'blur' }],
                Purchase_Amount: [{ required: true, message: '请输入订单金额', trigger: 'blur' }],
            },
            Goods: {},
            GoodsInfo: {},
            form: {
                Purchase_Order_SerialNumber: '',
                Supplier_SerialNumber: '',
                Purchase_Date: '',
                Purchase_Amount: 0,
                Paid_Amount: 0,
                Return_Amount: 0,
                Apply_Amount: 0,
                Confirm_Amount: 0,
                Enterprise_Info_SerialNumber: $.cookie("enterprise"),
                Transaction_Type: "",
                Children: {
                    purchase_order_detail: [{       //采购订单明细
                        Purchase_Order_Detail_SerialNumber: "",
                        Purchase_Order_SerialNumber: '',
                        Brand_SerialNumber: '',
                        Article_SerialNumber: '',
                        Article_Specifications_SerialNumber:'',
                        Article_UnitPrice: '',
                        Purchase_UnitPrice: '',
                        Quantity: 0,
                        Receipt_Quantity: 0,
                        Not_Receipt_Quantity: 0,
                        Shippment_Quantity: 0,
                        Inventory_Quantity: 0,
                        Amount: 0,
                        Unit_Price_SerialNumber: "",
                        Depot_Type: 0,
                        Store_SerialNumber: "",
                        article: []
                    }],
                    purchase_order_paystages: [{
                        Purchase_Order_Paystages_SerialNumber: "",
                        Purchase_Order_SerialNumber: "",
                        Trading_Explain: "",
                        Trading_Detail_SerialNumber: "",
                        Trading_Percentage: "",
                        Trading_Days: "",
                        Purchase_Amount: "",
                        Paid_Amount: 0,
                        Collection_Date: "",
                    }]
                }
            },
            supplier_info: [],
            // wholesale_unitprice_detail: [],
            Payway: [],
            Payment: [],
            RadioGroup: [],
            brand: [],
            arr: [],
            Wares: [],
            radio: 'Min_0',
            selected: 'Min_0',
            Transaction_Type: '0',
            selectedArr: [],
            paystages: {},
            loading: false
        }
    },
    mounted() {
        this.getData()
        this.getWares()
        this.Goods = JSON.parse(sessionStorage.getItem('GoodsData'))
        console.log(this.Goods)
        let Payway = this.Goods.Children.wholesale_unitprice_paystages
        Payway.forEach(item => {
            if ('Min_' + item.Min_Quantity in this.paystages) {
                if(item.Transaction_Type=='0'){
                    this.paystages['Min_' + item.Min_Quantity].Full_Payment = item
                }else{
                    this.paystages['Min_' + item.Min_Quantity].Payment_Days.push(item)
                }
            } else {
                this.paystages['Min_' + item.Min_Quantity] = {
                    Unit_Price:item.Unit_Price,
                    Full_Payment:{},
                    Payment_Days:[]
                }
                if(item.Transaction_Type=='0'){
                    this.paystages['Min_' + item.Min_Quantity].Full_Payment = item
                }else{
                    this.paystages['Min_' + item.Min_Quantity].Payment_Days = [item]
                }
                this.selectedArr.push({//给选中数组添加项
                    id: 'Min_' + item.Min_Quantity,
                    value: '方案' + toChinesNum(this.selectedArr.length + 1)
                })
            }
            console.log(this.paystages);
        })
        if( JSON.stringify(this.paystages[this.radio].Full_Payment) == '{}'){
            this.Transaction_Type = '1';
        }
        this.GoodsInfo = JSON.parse(sessionStorage.getItem('Goods'))
        console.log(this.GoodsInfo)
        this.form.Children.purchase_order_detail[0].Article_Name = this.GoodsInfo.Article_Name
        this.form.Children.purchase_order_detail[0].Brand_SerialNumber = this.GoodsInfo.Brand_SerialNumber
        this.form.Children.purchase_order_detail[0].Article_UnitPrice = this.GoodsInfo.Unit_Price
        this.form.Children.purchase_order_detail[0].Article_Specifications_SerialNumber = this.Goods.Article_Specifications_SerialNumber
        this.form.Children.purchase_order_detail[0].Article_SerialNumber = this.GoodsInfo.Article_SerialNumber
        this.form.Children.purchase_order_detail[0].Specifications_Name = this.Goods.Specifications_Name
        this.form.Children.purchase_order_detail[0].Quantity = parseInt(this.Goods.Starting_Quantity)
        this.form.Children.purchase_order_detail[0].Purchase_UnitPrice = this.paystages[this.radio].Unit_Price
        this.form.Children.purchase_order_detail[0].Amount = this.accMul(this.paystages[this.radio].Unit_Price,parseInt(this.Goods.Starting_Quantity))
        this.form.Purchase_Amount = this.accMul(this.paystages[this.radio].Unit_Price,parseInt(this.Goods.Starting_Quantity))
        this.getSupplierData(this.GoodsInfo.Enterprise_Info_SerialNumber)
    },
    computed: {
        transformed() {//计算
            return function (id) {
                let str = '';
                this.selectedArr.forEach(item => {
                    if (item.id == id) {
                        str = item.value
                    }
                })
                return str;
            }
        },
        AccMul() {	//浮点型相乘
            return function (arg1, arg2){
                let m = 0, s1 = arg1.toString(), s2 = arg2.toString();
                try { m += s1.split(".")[1].length } catch (e) { }
                try { m += s2.split(".")[1].length } catch (e) { }
                return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
            }
        }
    },
    methods: {
        getWares() {//获取所有可选仓库
            let this_ = this
            $.ajax({
                url: DomainName + '/getInquiryAction?token=' + $.cookie("token"),
                type: 'POST',
                data: {
                    Data: 'warehouse_info',
                },
                success: function (res) {
                    res.forEach(item => {
                        this_.Wares.push({
                            label: item.Warehouse_Name,
                            value: item.Applicable_Type == '0' ? item.Warehouse_SerialNumber : item.Parent_Warehouse_SerialNumber
                        })
                    })
                    console.log(this_.Wares)
                },
                dataType: "json"
            });
        },
        ChangeType(e){

        },
        getData() {
            const _this = this
            $.ajax({//获取供应商信息
                url: `${DomainName}/getInquiryAction?token=${$.cookie('token')}`,
                type: 'POST',
                data: {
                    Data: 'supplier_info'
                },
                success: function (res) {
                    _this.supplier_info = res;
                },
                error: function () {
                    _this.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    _this.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
            $.ajax({//获取品牌信息
                url: `${DomainName}/GoodsFileInquiry`,
                type: 'POST',
                data: {
                    Data: 'brand'
                },
                success: function (res) {
                    _this.brand = res;
                },
                error: function () {
                    _this.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    _this.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
        },
        getUnitPrice(e, id) {
            let arr = this.form.Children.purchase_order_detail[id].article
            arr.forEach(item => {
                if (item.Article_SerialNumber == e) {
                    this.form.Children.purchase_order_detail[id].Article_UnitPrice = item.Unit_Price
                }
            })

        },
        getSupplierData(Enterprise_Info_SerialNumber) {//获取对应企业供应商
            const _this = this
            $.ajax({
                url: DomainName + '/getSupplierInfoIDAction?token=' + $.cookie("token"),
                type: 'POST',
                data: {
                    Enterprise_Info_SerialNumber,
                },
                success: function (res) {
                    if (res.Status == 'success' && res.Data.length == 1) {
                        _this.form.Supplier_SerialNumber = res.Data[0].Supplier_SerialNumber
                    }
                },
                error: function () {
                    _this.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
        },
        count(e) {
            //计算适用方案
            let arr = []
            for (let key in this.paystages) {//遍历对象的key值用数组arr保存
                arr.push({
                    key,
                    num: parseInt(key.replace('Min_', ''))
                })
            }
            let newarr = this.sort(arr).reverse() //新数组保存arr数组
            for (let i = 0; i < newarr.length; i++) {//遍历数组
                if (newarr[i].num <= parseInt(e)) {//如果小于等于输入的值就等于新数组的选中项
                    this.selected = newarr[i].key
                    break;
                }
            }
            this.radio = this.selected
            this.form.Children.purchase_order_detail[0].Purchase_UnitPrice = this.paystages[this.radio].Unit_Price
            this.form.Children.purchase_order_detail[0].Amount = this.accMul(this.paystages[this.radio].Unit_Price,parseInt(e))
            this.form.Purchase_Amount = this.accMul(this.paystages[this.radio].Unit_Price,parseInt(e))
            //计算金额
        },
        sort(arr) {//数组冒泡排序
            for (var i = 0; i < arr.length - 1; i++) {
                for (var j = 0; j < arr.length - 1 - i; j++) {
                    if (arr[j].num > arr[j + 1].num) {
                        var temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
            return arr
        },
        accMul(arg1, arg2) {	//浮点型相乘
            let m = 0, s1 = arg1.toString(), s2 = arg2.toString();
            try { m += s1.split(".")[1].length } catch (e) { }
            try { m += s2.split(".")[1].length } catch (e) { }
            return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
        },
        accAdd(arg1, arg2) {	//浮点型相加
            var r1, r2, m;
            try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
            try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
            m = Math.pow(10, Math.max(r1, r2))
            return (arg1 * m + arg2 * m) / m
        },
        submitForm() {//提交
            let _this = this
            _this.form.Purchase_Date = getYMDHMSDate()
            _this.form.Transaction_Type = _this.Transaction_Type
            _this.form.Children.purchase_order_detail[0].Unit_Price_SerialNumber = _this.Goods.Wholesale_Unit_Price_SerialNumber
            _this.form.Children.purchase_order_paystages = []
            if (_this.Transaction_Type == '1') {
                _this.paystages[_this.selected].Payment_Days.forEach(item => {
                    _this.form.Children.purchase_order_paystages.push({
                        Purchase_Order_Paystages_SerialNumber: "",
                        Purchase_Order_SerialNumber: "",
                        Trading_Explain: item.Trading_Explain,
                        Trading_Detail_SerialNumber: item.Trading_Detail_SerialNumber,
                        Trading_Percentage: item.Trading_Percentage,
                        Trading_Days: item.Trading_Days,
                        Purchase_Amount: Number(item.Trading_Percentage) * Number(_this.form.Children.purchase_order_detail[0].Amount) / 100,
                        Paid_Amount: 0,
                        Collection_Date: "",
                    })
                })
            } else {
                let item = _this.paystages[_this.selected].Full_Payment
                _this.form.Children.purchase_order_paystages = [{
                    Purchase_Order_Paystages_SerialNumber: "",
                    Purchase_Order_SerialNumber: "",
                    Trading_Explain: item.Trading_Explain,
                    Trading_Detail_SerialNumber: item.Trading_Detail_SerialNumber,
                    Trading_Percentage: 100,
                    Trading_Days: item.Trading_Days,
                    Purchase_Amount: Number(_this.form.Children.purchase_order_detail[0].Amount)*Number(item.Trading_Percentage)/100,
                    Paid_Amount: 0,
                    Collection_Date: "",
                }]
                _this.form.Purchase_Amount = Number(_this.form.Children.purchase_order_detail[0].Amount)*Number(item.Trading_Percentage)/100
            }
            console.log(_this.form)
            let data = {
                Data: JSON.stringify({
                    purchase_order: [_this.form]
                })
            }
            $.ajax({
                url: DomainName + '/setPurchaseOrderAction?token=' + $.cookie("token"),
                type: 'POST',
                data,
                success: function (res) {
                    console.log(res)
                    if (res.Status == 'success') {
                        _this.$message({
                            message: '提交成功',
                            type: 'success'
                        });
                        window.history.go(-1)
                    }
                },
                error: function () {
                    _this.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    _this.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
        },
        CheckStore(formName) {//检查库存
            if(this.form.Children.purchase_order_detail[0].Store_SerialNumber==''){
                this.$message({
                    message: '请选择仓库后再提交',
                    type: 'error'
                })
                return
            }
            let _this = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    _this.loading = true
                    $.ajax({
                        url: DomainName + '/getArticleCheckStockAction?token=' + $.cookie("token"),
                        type: 'POST',
                        data: {
                            Wholesale_Unit_Price_SerialNumber: _this.Goods.Wholesale_Unit_Price_SerialNumber,
                            Quantity: _this.form.Children.purchase_order_detail[0].Quantity,
                        },
                        success: function (res) {
                            console.log(res)
                            if (res.Status == 'success') {
                                _this.submitForm()
                            } else if (res.Status == 'fail') {
                                _this.loading = false
                                _this.$message.error("该商品库存不足")
                            }
                        },
                        error: function () {
                            _this.$message.error("操作失败，请稍后再试")
                        },
                        complete: function (XMLHttpRequest) {
                            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                                window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                            }
                        }
                    })
                } else {
                    _this.$message.error("请检查是否有漏填项")
                }
            });
        },
        Pricethousands(num) {//转千分位
            return thousands(num)
        },
    }
})